package com.diver.flinkdemo.utils;

/**
 * @author hesc
 * @date 2022-03-11
 */
public class UnicodeUtil {

    //unicode 转字符串
    public static String unicodeToString(String unicode) {
        StringBuffer string = new StringBuffer();
        String[] hex = unicode.split("\\\\u");
        for (int i = 1; i < hex.length; i++) {
            int data = Integer.parseInt(hex[i], 16);// 转换出每一个代码点
            string.append((char) data);// 追加成string
        }
        return string.toString();
    }

    public static String unicodeToStrings(String unicode) {
        String str = "0123456789ABCDEF";
        char[] hexs = unicode.toCharArray();
        byte[] bytes = new byte[unicode.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    //字符串转换unicode
    public static String stringToUnicode(String string) {
        StringBuffer unicode = new StringBuffer();
        for (int i = 0; i < string.length(); i++) {
            char c = string.charAt(i);  // 取出每一个字符
            unicode.append("\\u" +Integer.toHexString(c));// 转换为unicode
        }
        return unicode.toString();
    }

    public static String stringToUnicodes(String str) {
        StringBuffer sb = new StringBuffer();
        char[] c = str.toCharArray();
        for (int i = 0; i < c.length; i++) {
            String hex = Integer.toHexString(c[i]);
            if (hex.length() < 4) {
                switch (hex.length()) {
                    case 1:
                        hex = "000" + hex;
                        break;
                    case 2:
                        hex = "00" + hex;
                        break;
                    case 3:
                        hex = "0" + hex;
                        break;
                }
            }
            sb.append(hex);
        }
        return sb.toString().toUpperCase();
    }
}
